package com.nulldev.util.web.flexibleKit.scfk.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.nulldev.util.io.IOUtils;
import com.nulldev.util.web.HttpServer3.util.MarkableInputStream;
import com.nulldev.util.web.flexibleKit.scfk.io.streams.Stream;

public class SCFKIOUtils {

	public static InputStream make(final Stream s) {
		return new MarkableInputStream(new InputStream() {

			@Override
			public int read() throws IOException {
				final ByteBuffer b = ByteBuffer.allocate(1);
				final int o = s.read(b);
				if (o == -1)
					return -1;
				return b.get();
			}

			@Override
			public int read(byte[] b) throws IOException {
				final ByteBuffer bf = ByteBuffer.wrap(b);
				return (int) s.read(bf);
			}

			@Override
			public int read(byte[] b, int off, int len) throws IOException {
				final ByteBuffer bf = ByteBuffer.wrap(b, off, len);
				return (int) s.read(bf);
			}

			@Override
			public void close() throws IOException {
				super.close();
				s.closeIfNeeded();
			}
		}, IOUtils.MEMORY_ALLOC_BUFFER);
	}
}
